//
//  BaseTableModelVC.m
//  JadeShop
//
//  Created by mac on 2019/5/24.
//  Copyright © 2019年 SZJ.test. All rights reserved.
//

#import "BaseTableModelVC.h"
#import "NetWorkTool.h"
#import "BaseTableViewCell.h"
#import "BaseTableViewHeaderFooterView.h"
#import "BaseModel.h"
#import "Tool.h"
@interface BaseTableModelVC ()<TableViewCellDelegate,BaseTableViewHeaderFooterViewDelegate>

@property (nonatomic,strong) NSString * cellClassStr;

@property (nonatomic) Class modelClass;

@property (nonatomic,copy) NSString * layoutRule;
@property (nonatomic,strong) NSDictionary * params;
@property (nonatomic,assign) CC_RefreshType needRefresh;

@end

@implementation BaseTableModelVC
{
    NSMutableArray <NSArray <NSString *> *> * _hfArr;
    NSArray <NSString *> *_headerClassArr;
    NSArray <NSString *> *_footerClassArr;
    NSMutableArray <NSString *> *_headerCacheArr;
    NSMutableArray <NSString *> *_footerCacheArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.tableView isGroup];
    _hfArr = [NSMutableArray array];
    _footerCacheArr = [NSMutableArray array];
    _headerCacheArr = [NSMutableArray array];
    [self gethHFClass];
}

- (void)beginWithModelBlock:(VCModelSet)modelBlock{
    Class modelClass;
    NSDictionary *params;
    CC_RefreshType needRefresh;
    NSString *layoutRule;
    modelBlock(&modelClass,&needRefresh,&params,&layoutRule);
    if (modelClass) self.modelClass = modelClass;
    if (params) self.params = params;
    if (needRefresh) self.needRefresh = needRefresh;
    if (layoutRule) self.layoutRule = layoutRule;
    [self getData:1];
}






-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.dataSource.count > 0 && [self.dataSource[0] isKindOfClass:NSArray.class]) {
        return self.dataSource.count;
    }
    if (tableView.style == UITableViewStyleGrouped) return self.dataSource.count;
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataSource.count > 0 && [self.dataSource[0] isKindOfClass:NSArray.class]) {
        return [self.dataSource[section] count];
    }
    if (tableView.style == UITableViewStyleGrouped)  return 1;
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseModel <BaseCellModelProtocol> * model = self.dataSource[tableView.style == UITableViewStyleGrouped ? indexPath.section : indexPath.row];
    NSString *cellClassStr = [model cellClassStr];
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellClassStr];
    if (!cell) cell = [[NSBundle mainBundle] loadNibNamed:cellClassStr owner:nil options:nil][0];
    cell.indexPath = indexPath;
    cell.model = model;
    cell.cellEvent = self.eventCallBack;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseModel <BaseCellModelProtocol> * model = self.dataSource[tableView.style == UITableViewStyleGrouped ? indexPath.section : indexPath.row];
    NSString *cellClassStr = [model cellClassStr];
    Class cellClass = NSClassFromString(cellClassStr);
    return [cellClass cellHeight:model];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BaseTableViewHeaderFooterView *header = nil;
    if (self.HFClass) {
        NSString *headerClass = [self getHFClass:section forFooter:NO];
        
        if (headerClass.length == 0) return header;
            Class Header = NSClassFromString(headerClass);
            if (Header) {
                header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerClass];
                if (!header)header = [[NSBundle mainBundle] loadNibNamed:headerClass owner:nil options:nil][0];
                [header setSection:section];
                [header setDelegate:self];
                if (self.HFModel) [header setModel:self.HFModel(section,YES)];
                header.HFEvent = self.eventCallBack;
            }
    }
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.HFClass) {
        Class Header = NSClassFromString([self getHFClass:section forFooter:NO]);
        if (Header) return [Header viewSize:nil withSection:section];
    }
    return CGFLOAT_MIN;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    BaseTableViewHeaderFooterView *header = nil;
    if (self.HFClass) {
        NSString *headerClass = [self getHFClass:section forFooter:YES];
        
        if (headerClass.length == 0) return header;
        Class Header = NSClassFromString(headerClass);
        if (Header) {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerClass];
            if (!header)header = [[NSBundle mainBundle] loadNibNamed:headerClass owner:nil options:nil][0];
            [header setSection:section];
            [header setDelegate:self];
            if (self.HFModel) [header setModel:self.HFModel(section,NO)];
            header.HFEvent = self.eventCallBack;
        }
    }
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.HFClass) {
        Class Header = NSClassFromString([self getHFClass:section forFooter:YES]);
        if (Header) return [Header viewSize:nil withSection:section];
    }
    return CGFLOAT_MIN;
}

- (NSString *)getHFClass:(NSInteger)section forFooter:(BOOL)isFooter{
    
    if (isFooter && _footerCacheArr.count > section) return _footerCacheArr[section];
    if (!isFooter && _headerCacheArr.count > section) return _headerCacheArr[section];
    
    NSString *classStr;
    NSArray <NSString *>*hf;
    
    if (section >= _hfArr.count) {
        hf = _hfArr[section];
    }else{
        hf = _hfArr.lastObject;
    }
    
    NSString * index;
    
    if (hf.count == 2) {
        //两个就说明是正常数据
        index = hf[isFooter];
    }else{
        //1个说明是重复 数据 （1,2）(4,2),(2) 4想要的
        NSInteger trueIndex = hf[0].integerValue;//正确的index
        index = _hfArr[trueIndex][isFooter];
    }
    
    classStr = [index isEqualToString:@"n"] ? @"" : hf[index.integerValue];
    
    if (isFooter) {
        [_footerCacheArr addObject:classStr];
    }else{
        [_headerCacheArr addObject:classStr];
    }
    return classStr;
}

- (void)getData:(NSInteger)page{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:self.params];
    if (self.needRefresh) params[@"page"] = @(page);
    if (![self.modelClass api]) {
        [self.tableView reloadData];
        return;
    }
    [self.modelClass getDataWithParams:self.params WithCallBack:^(id data) {
            self.model = data;
            if (self.page == 1) {
                [self.dataSource removeAllObjects];
            }
            if (self.handleData) {
                self.handleData();
            }else
            {
                for (__kindof BaseModel *dataModel in [self.model dataArr]) {
                    [self.dataSource addObject:dataModel];
                }
                [self.tableView cc_endReFresh:[self.model dataArr]];
            }
    }];
}


- (void)repeatGetData{
    _page = 1;
    [self getData:1];
}

-(void)setNeedRefresh:(CC_RefreshType)needRefresh{
    _needRefresh = needRefresh;

    switch (_needRefresh) {
        case CC_RefreshTypeAll:
            [self needHeaderRefresh];
            [self needFooterRefresh];
            break;
        case CC_RefreshTypeHeader:
            [self needHeaderRefresh];
            self.tableView.mj_footer = nil;
            break;
        case CC_RefreshTypeFooter:
            self.tableView.mj_header = nil;
            [self needFooterRefresh];
            break;
        default:
            self.tableView.mj_header = nil;
            self.tableView.mj_footer = nil;
            break;
    }
}

-(void)gethHFClass{
    if (self.HFClass && (!_headerClassArr && !_headerClassArr)) {
        NSArray * headerClassArr;
        NSArray * footerClassArr;
        self.HFClass(&headerClassArr, &footerClassArr);
        if (headerClassArr) {
            _headerClassArr = headerClassArr;
        }
        if (footerClassArr) {
            _footerClassArr = footerClassArr;
        }
    }
}

-(void)setLayoutRule:(NSString *)layoutRule{
    _layoutRule = [layoutRule copy];
    [_hfArr removeAllObjects];
    NSArray <NSString *> *sectionArr = [layoutRule componentsSeparatedByString:@"~"];
    for (int i = 0; i < sectionArr.count; i++) {
        NSString *sectionStr = sectionArr[i];
        NSString *firstStr = [sectionStr substringToIndex:1];
        if ([firstStr isEqualToString:@"r"]) {
            if ([sectionStr isEqualToString:@"rx"]) {
                [_hfArr addObject:@[IntToString(i - 1)]];
            }else{
                NSInteger repeatCount = [sectionStr stringByReplacingOccurrencesOfString:@"r" withString:@""].integerValue;
                for (int j = 0; j < repeatCount; j++) {
                    [_hfArr addObject:@[IntToString(i - j - 1)]];
                }
            }
        }else{
            NSArray <NSString *> *strArr = [sectionStr componentsSeparatedByString:@"-"];
            [_hfArr addObject:strArr];
        }
    }
}


-(void)needHeaderRefresh{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self repeatGetData];
    }];
}

-(void)needFooterRefresh{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getData:self.page];
    }];
}

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}





@end


